package com.wl.config;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class DataSourceAspect {  

    @Pointcut("@annotation(com.wl.config.DataSourceKey)")
    public void pointcut(){};

    @Before("pointcut()")
    public void changeDataSource(JoinPoint point) {
        String key = dataSourceKey(point).value();
        DataSourceContextHolder.setDataSourceKey(key);  
    }  
  
    @After("pointcut()")
    public void clearDataSource(JoinPoint point) {
        DataSourceContextHolder.clearDataSourceKey();  
    }


    public DataSourceKey dataSourceKey(JoinPoint point){
        Signature signature = point.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        return method.getAnnotation(DataSourceKey.class);
    }
}